package com.easymall.web;

import com.easymall.domain.User;
import com.easymall.service.UserService;
import com.easymall.util.BaseFactory;
import com.easymall.util.FormValidation;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {

    private UserService userService;

    @Override
    public void init() throws ServletException {
        try {
            userService = BaseFactory.getFactory().getInstance(UserService.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remname = request.getParameter("remname");
        String autologin = request.getParameter("autologin");

        // 2、 参数验证
        ArrayList<String> errorList = null;
        Map<String, List<String>> errorMsg = FormValidation.validationUsername("username", username);
        if (null == password || "".equals(password)) {
            errorList = new ArrayList<String>(1);
            errorList.add("密码不能为空！");
            errorMsg.put("password", errorList);
        }

        // 3、 验证用户名密码
        if (0 == errorMsg.size()) {
            errorList = new ArrayList<String>(1);
            try {
                User user = userService.login(username, password);
                if (null == user) {
                    errorList.add("用户名或密码错误！");
                } else {
                    HttpSession session = request.getSession();
                    session.setAttribute("user", user);
                    if ("true".equals(autologin)) {
                        // 勾选了30天自动登录，使用User对象的hash值做为autologin的值
                        String key = "autologin";
                        String value = String.valueOf(user.getId()) + "#" + new BigInteger(String.valueOf(user.hashCode())).toString(16);
                        Cookie autologinCookie = new Cookie(key, value);
                        autologinCookie.setMaxAge(30*24*3600);
                        autologinCookie.setPath(request.getServletContext().getContextPath()+"/");
                        response.addCookie(autologinCookie);
                    }
                    if ("true".equals(remname)) {
                        String key = "remname";
                        Cookie remnameCookie = new Cookie(key, username);
                        remnameCookie.setMaxAge(30*24*3600);
                        remnameCookie.setPath(request.getContextPath());
                        response.addCookie(remnameCookie);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
                errorList.add("登陆失败，请稍候重试！");
            }
            if (errorList.size() != 0) {
                errorMsg.put("all", errorList);
            }
        }

        // 4、 响应请求
        if (0 == errorMsg.size()) {
            response.sendRedirect("/index.jsp");
        } else {
            request.setAttribute("errorMsg", errorMsg);
            doGet(request, response);
        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}
